home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10981 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: interramp.com!usenet
  2. From: us011245@interramp.com
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Virtual Base Class
  5. Date: Sun, 10 Mar 96 17:01:58 PDT
  6. Organization: PSI Public Usenet Link
  7. Message-ID: <NEWTNews.24289.826506668.hampton@interramp.com>
  8. References: <4i1gnv$b7i@uuneo.neosoft.com>
  9. NNTP-Posting-Host: ip108.herndon7.va.interramp.com
  10. Mime-Version: 1.0
  11. Content-Type: TEXT/PLAIN; charset=US-ASCII
  12. X-Newsreader: NEWTNews & Chameleon -- TCP/IP for MS Windows from NetManage
  13.  
  14.  
  15. In article <4i1gnv$b7i@uuneo.neosoft.com>, <Wmatthew@lan-aces.com> writes:
  16. > In article <313F98D0.102E@ucla.edu>, Dennis Rahaman <dennisr@ucla.edu> says:
  17. > >
  18. > >This is what I want to do:
  19. > >
  20. > >              a
  21. > >            /   \
  22. > >           b     c
  23. > >            \   /
  24. > >              d
  25. > >
  26. > >
  27. > >class a
  28. > >  {
  29. > >  //...
  30. > >  };
  31. > >
  32. > >class b : public virtual a
  33. > >  {
  34. > >  //...
  35. > >  };
  36. > >
  37. > >class c : public virtual b
  38. > >  {
  39. > >  //...
  40. > >  };
  41. > >
  42. > >class d : public b, public c
  43. > >  {
  44. > >  //...
  45. > >  };
  46. > >
  47. > >
  48. > >void f ()
  49. > >  {
  50. > >  a a1;
  51. > >  d* pd = (d*) &a1;  // error: can't cast virtual base to derived
  52. > >  }
  53. > >
  54. > >///////////////////////////////////////////////////////////
  55. > >Can someone explain why I can't cast a virtual base class to a derived 
  56. > >class?
  57. > >
  58. The way you've presented it, a1 is a member of class a.  The fact that class a 
  59. is a virtual base class for class d doesn't mean that all objects of class a 
  60. are really objects of class d.  I think you're confusing the idea of a virtual 
  61. base class with the idea of a pure virtual function.  In the sense of 
  62. inheritance, what virtual does is to ensure that you don't get more than one 
  63. copy of the base class in a multiple inheritance situation.  For example, if 
  64. you had left the virtual keyword out above, class d would have two copies of 
  65. all class a's attributes--one copy inherited from class b and one copy 
  66. inherited from class c.  All that virtual does here is tell the compiler to use 
  67. only one copy of class a, even though two are implied by the inheritance.  This 
  68. has nothing to do with whether objects of class a can exist that are not 
  69. actually elements of class d.
  70.  
  71. regards,
  72. Luther Hampton  
  73.  
  74.